<?php

namespace apps\api\modules\article\controllers;

use common\map\CommonMap;
use common\modules\user\logic\UserAuthorLevelLogic;
use Yii;
use common\modules\article\ArticleComment;

class ArticleCommentController extends \apps\api\modules\ApiBaseController
{
    public $modelClass = 'common\modules\article\ArticleComment';

    public function actionView($id)
    {
        try {
            $data = ArticleComment::findOne($id);
            UserAuthorLevelLogic::reward($this->userId, 'Read');
            return $this->returnData($data);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionMyIndex($page)
    {
        try {
            $list = ArticleComment::getModel($page)
                ->where(['userId' => $this->userId, 'status' => CommonMap::BOOLEAN_YES])
                ->with(['user' => function ($q) {
                    $q->select(['userId', 'avatar', 'sqc', 'nickname']);
                }])
                ->asArray()
                ->all();
            return $this->returnList($list);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionIndex($page, $articleId, $parentId = null)
    {
        try {
            $list = ArticleComment::getModel($page)
                ->filterWhere(['articleId' => $articleId, 'status' => CommonMap::BOOLEAN_YES, 'parentId' => $parentId])
                ->with(['user' => function ($q) {
                    $q->select(['userId', 'avatar', 'sqc', 'nickname']);
                }])
                ->asArray()
                ->all();
            return $this->returnList($list);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionCreate($id)
    {
        $db = ArticleComment::getDb()->beginTransaction();
        try {
            $isFirst = empty(ArticleComment::findOne($id));
            $m =  new ArticleComment;
            $m->articleId = $id;
            $m->userId = $this->userId;
            $m->content = Yii::$app->request->post('content');
            $m->logicSave();
            $isFirst && UserAuthorLevelLogic::reward($this->userId, 'Comment');
            $db->commit();
            return $this->returnData($m);
        } catch (\Exception $e) {
            $db->rollBack();
            return $this->returnExceptionError($e);
        }
    }

    public function actionDelete($id)
    {
        try {
            ArticleComment::logicFindOne(['userId' => $this->userId, 'articleId' => $id])->delete();
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }
}
